package com.toplabs.unashu.interceptor;

import cn.dev33.satoken.interceptor.SaRouteInterceptor;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author toplabs
 * @since 2022/08/09
 * <p>This java file was created by toplabs in 2022/08/09.
 * The following is the description information about this file:</p>
 * <p>description: 身份验证拦截器</p>
 */
@Slf4j
@Component
public class AuthInterceptor extends SaRouteInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 登录验证 -- 拦截所有路由，并排除/user/login 用于开放登录
        SaRouter.match("/**")
                .notMatch("/auth/token", "/auth/refresh", "/system/install", "/config/detail/*")
                .check(StpUtil::checkLogin);
        // 角色认证 -- 拦截以 admin 开头的路由，必须具备[admin]角色或者[super-admin]角色才可以通过认证
        SaRouter.match("/admin/**", () -> StpUtil.checkRoleOr("admin", "super-admin"));
        SaRouter.match("/user/**")
                .notMatch("/user/info/*")
                .check(() -> StpUtil.checkRoleOr("user", "super-admin"));
        return true;
    }
}
